package net.oschina.arvin.sqlbuilder.definition;

import net.oschina.arvin.sqlbuilder.WhereBuilder;
import net.oschina.arvin.sqlbuilder.enums.CompareType;
import net.oschina.arvin.sqlbuilder.exceptions.SqlBuilderException;
import net.oschina.arvin.sqlbuilder.utils.AssertUtil;
import net.oschina.arvin.sqlbuilder.utils.Util;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Arvin
 * @time 2017/11/17 20:23
 */
public class DirectGeneralConditionItem extends AbstractGeneralConditionItem {

    private static Set<CompareType> supportCompareTypeSet = new HashSet<CompareType>(Arrays.asList(
            CompareType.EQUAL, CompareType.IS_NOT_NULL, CompareType.IS_NULL, CompareType.NOT_EQUAL
    ));

    /** 用于查询的值 */
    private final Object value;

    public DirectGeneralConditionItem(ColumnDefinition modelColumnDefinition, Object value, CompareType compareType) {
        super(modelColumnDefinition, compareType);
        AssertUtil.assertNotNull(value, "Map比较条件，要比较的值不能为null");
        this.value = value;
    }

    @Override
    protected boolean isSupportCompareType(CompareType compareType) {

        if (supportCompareTypeSet.contains(compareType)) {
            return true;
        }

        // 字符串类型才支持 LIKE 查询
        Class<?> fieldType = value.getClass();
        if (Util.isStringType(fieldType) && CompareType.LIKE.equals(compareType)) {
            return true;
        }

        return false;
    }

    @Override
    protected boolean customAppendToWhereBuilder(Object queryCondition, WhereBuilder whereBuilder, CompareType compareType) {
        String unWrapColumnName = getModelColumnDefinition().getUnWrapColumnName();

        switch (compareType) {
            case EQUAL:
                whereBuilder.equal(true, unWrapColumnName, value);
                break;
            case NOT_EQUAL:
                whereBuilder.notEqual(true, unWrapColumnName, value);
                break;
            case LIKE:
                whereBuilder.like(true, unWrapColumnName, String.valueOf(value));
                break;
            case IS_NULL:
                whereBuilder.andIsNull(unWrapColumnName);
                break;
            case IS_NOT_NULL:
                whereBuilder.andIsNotNull(unWrapColumnName);
                break;
            default:
                throw new SqlBuilderException("不支持的比较类型！");
        }

        return true;
    }


}
